package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.OrderDetailVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IKsOrderService;
import com.ruoyi.system.utils.CardNumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 客诉工单Controller
 *
 * @author hjf
 * @date 2025-07-10
 */
@RestController
@RequestMapping("/hmk/ksOrder")
public class KsOrderController extends BaseController {
    @Autowired
    private IKsOrderService ksOrderService;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RxOrderMapper oM;
    @Autowired
    private RxOrderFollowMapper oFM;

    @Autowired
    private KsReplyLogMapper kRLM;

    @Autowired
    private OrderChannelMapper oCM;

    /**
     * 查询客诉工单列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(KsOrder ksOrder) {
        startPage();
        List<KsOrder> list = ksOrderService.selectKsOrderList(ksOrder);
        for (KsOrder oldKsOrder : list) {
            if (oldKsOrder.getState() == 5) {
                String timeDistance = DateUtils.timeDistance2(oldKsOrder.getCreateTime(), oldKsOrder.getWanJieTime());
                oldKsOrder.setTitleAndTime(oldKsOrder.getTitle() + " " + timeDistance);
                oldKsOrder.setHandleTime(timeDistance);
            } else if (oldKsOrder.getState() == 6) {
                String timeDistance = DateUtils.timeDistance2(oldKsOrder.getCreateTime(), oldKsOrder.getCloseTime());
                oldKsOrder.setTitleAndTime(oldKsOrder.getTitle() + " " + timeDistance);
                oldKsOrder.setHandleTime(timeDistance);
            } else {
                oldKsOrder.setTitleAndTime(oldKsOrder.getTitle());
                String timeDistance = DateUtils.timeDistance2(oldKsOrder.getCreateTime(), new Date());
                oldKsOrder.setHandleTime(timeDistance);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出客诉工单列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksOrder:export')")
    //@Log(title = "客诉工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KsOrder ksOrder) {
        List<KsOrder> list = ksOrderService.selectKsOrderList(ksOrder);
        ExcelUtil<KsOrder> util = new ExcelUtil<KsOrder>(KsOrder.class);
        util.exportExcel(response, list, "客诉工单数据");
    }

    /**
     * 获取客诉工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ksOrderService.selectKsOrderById(id));
    }


    @GetMapping(value = "/selectRxOrderBySerial/{serial}")
    @PermitAll
    public AjaxResult selectRxOrderBySerial(@PathVariable("serial") String serial) {
        OrderDetailVo orderDetailVo = oM.selectRxOrderBySerial(serial);
        if (null != orderDetailVo && StringUtils.isNotEmpty(orderDetailVo.getCustomNumber())) {
            orderDetailVo.setCustomNumberAge(CardNumberUtils.calculateAge(orderDetailVo.getCustomNumber()) + "岁");
        }
        return success(orderDetailVo);
    }

    @GetMapping(value = "/selectUsersByIds")
    @PermitAll
    public AjaxResult selectUsersByIds() {
        return success(sysUserMapper.selectUsersByIds(new SysUser()));
    }

    /**
     * 新增客诉工单
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksOrder:addKsOrder')")
    //@Log(title = "客诉工单", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addKsOrder")
    @RepeatSubmit
    public AjaxResult addKsOrder(@RequestBody KsOrder ksOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        if (StringUtils.isEmpty(sysUser.getNickName())) {
            sysUser = sysUserMapper.selectUserById(sysUser.getUserId());
        }

        Date createTime = new Date();
        ksOrder.setCreateBy(String.valueOf(sysUser.getUserId()));
        String orderId = ksOrder.getOrderId();
        RxOrder oldOrder = oM.selectRxOrderById(Long.valueOf(ksOrder.getOrderId()));
        String ksType = "";
        switch (ksOrder.getKsType()) {
            case 1:
                ksType = "赠款赔偿";
                break;
            case 2:
                ksType = "变更套餐";
                break;
            case 3:
                ksType = "装机移机";
                break;
            case 4:
                ksType = "取消协议";
                break;
            case 5:
                ksType = "拆机销户";
                break;
            default:
                ksType = "没传值";
        }
        ksOrder.setState(1);
        String title = "";
        if (StringUtils.isNotEmpty(oldOrder.getCustomName())) {
            title += oldOrder.getCustomName();
        }
        if (StringUtils.isNotEmpty(oldOrder.getTelnumber())) {
            title += oldOrder.getTelnumber();
        }

        String nickName = "";
        if (StringUtils.isNotEmpty(oldOrder.getChannelId())) {
            OrderChannel orderChannel = oCM.selectOrderChannelById(Long.valueOf(oldOrder.getChannelId()));
            SysUser channelUser = sysUserMapper.selectUserById(orderChannel.getSupportId());
            if (null != channelUser) {
                ksOrder.setSupportId(orderChannel.getSupportId());
                nickName = channelUser.getNickName();
            }
        } else {
            ksOrder.setSupportId(92L);
            nickName = "邓玲";
        }

        title = title + ksType + "工单";
        ksOrder.setTitle(title);
        ksOrder.setKsId("KS" + DateUtils.dateTimeNow2());
        ksOrder.setOrderId(oldOrder.getSerial());
        ksOrder.setSupportIsRes(0);
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setTitle("【创建客诉工单】");
        rxOrderFollow.setOrderId(Integer.valueOf(orderId));
        rxOrderFollow.setManageId(sysUser.getUserId().intValue());
        rxOrderFollow.setContent(sysUser.getNickName() + "创建了客诉工单【" + title + "】工单号为" + ksOrder.getKsId());
        rxOrderFollow.setTime(System.currentTimeMillis() / 1000);
        oFM.insertRxOrderFollow(rxOrderFollow);

        ksOrderService.insertKsOrder(ksOrder);
        KsReplyLog ksR4 = new KsReplyLog();
        ksR4.setOrderId(oldOrder.getSerial());
        ksR4.setKsId(ksOrder.getId());
        ksR4.setReplyContent("【创建客诉工单】" + sysUser.getNickName() + "创建了客诉工单【" + title + "】工单号为" + ksOrder.getKsId());
        ksR4.setReplyUserId(sysUser.getUserId());
        ksR4.setCreateTime(createTime);
        kRLM.insertKsReplyLog(ksR4);

        KsReplyLog ksRL = new KsReplyLog();
        ksRL.setOrderId(oldOrder.getSerial());
        ksRL.setKsId(ksOrder.getId());

        ksRL.setReplyContent("【分配专员处理】" + "此客诉工单已自动分配给" + nickName + ",请尽快处理");
        ksRL.setReplyUserId(sysUser.getUserId());
        ksRL.setCreateTime(createTime);
        kRLM.insertKsReplyLog(ksRL);
        return AjaxResult.success();
    }


    /**
     * 修改客诉工单
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksOrder:edit')")
    //@Log(title = "客诉工单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KsOrder ksOrder) {
        return toAjax(ksOrderService.updateKsOrder(ksOrder));
    }

    /**
     * 删除客诉工单
     */
    @PreAuthorize("@ss.hasPermi('hmk:ksOrder:remove')")
    //@Log(title = "客诉工单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ksOrderService.deleteKsOrderByIds(ids));
    }


}
